"use client";

import {
  Button,
  Col,
  Divider,
  Form,
  message,
  Modal,
  Radio,
  RadioChangeEvent,
  Row,
  Select,
  Table,
} from "antd";
import { useEffect, useState } from "react";
import {
  AddImproveLines,
  GetImproveCount,
  GetImproveData,
  GetUinfoImprove,
  UpdateAccFlag,
} from "@/app/api/operation/improve";
import { useSearchParams } from "next/navigation";
import { getUserAccount } from "../../../../utils/defender";
import {
  ImproveData,
  ImproveDataLines,
  ImproveUinfo,
} from "../../../../utils/publictype";
import { IoAddCircle } from "react-icons/io5";
import { MdEdit, MdDelete, MdOutlineWarningAmber } from "react-icons/md";
import {
  improveRadio,
  improveTheme,
  selectOptions,
  tablesettingArrImprove,
} from "../../../../utils/static-select";
import DetailForm from "@/components/DetailForm";
import {
  SaveOutlined,
  SendOutlined,
  SignatureOutlined,
} from "@ant-design/icons";
import { TableDataType } from "../../../../utils/publicFuc";
import { useRouter } from "next/navigation";
import SignCom from "@/components/Sign";
import { FaCircleArrowLeft } from "react-icons/fa6";
import { UserModalOp } from "@/components/UserModal";

//#region Import

//#endregion

export default function Improve() {
  //#region state
  const router = useRouter();
  const param = useSearchParams();
  const [form] = Form.useForm();
  const [curSeq, setCurSeq] = useState(1);//記錄當前improve seq count
  const [UInfo, setUInfo] = useState<ImproveUinfo>();//表頭數據，包括狀態記錄
  const [editable, setEditalbe] = useState(false);
  const [editable2, setEditable2] = useState(false);
  const [dataSource, setDataSource] = useState<ImproveData>({
    docid: param.get("docid") as string,
    seq: 1,
    improvement_theme: "",
    improvement_result: "",
    interview_date: "",
    last_update_by: "",
    lines: [],
  });//明細數據
  const [isModalOpen, setIsModalOpen] = useState(false);
  const [operation, setOperation] = useState("");//表單操作記錄
  const [initialRow, setInitialRow] = useState<ImproveDataLines>();//點擊新增時輸入格式
  const [modifyRow, setModifyRow] = useState<ImproveDataLines>();//點擊修改時初始參數代入
  const [flowtype, setFlowType] = useState("record");//各流程進入影響表單各權限的狀態
  const [changeFlag, setChangeFlag] = useState(0);//用於父組件state變化導致在組件沒有及時渲染而處理的Flag
  const [sytanxFlag, setSytanxFlag] = useState(false);//異常Flag，將所有按鈕禁用
  const [signModalOpen, setSignModalOpen] = useState(false);//簽名組件openFlag
  const [status, setStatus] = useState("");//各流程進入影響表單各權限的狀態
  const [curSelSeq, setCurSelSeq] = useState(1);//記錄當前improve seq，用戶查詢與數據更新。
  //#endregion

  //#region 初始化
  useEffect(() => {
    GetImproveCount(param.get("docid") as string).then((res: any) => {
      setCurSeq(res[0][0].count);//獲取Seq
      getInitData(res[0][0].count);//默認選最大Seq
    });
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []);

  const getInitData = async (seq: number) => {
    //先將明細數據清空
    setCurSelSeq(seq);
    setDataSource({
      docid: param.get("docid") as string,
      seq: seq,
      improvement_theme: "",
      improvement_result: "",
      interview_date: "",
      last_update_by: "",
      lines: [],
    });
    form.setFieldValue("improvement_theme", "");
    try {
      const res: any = await GetUinfoImprove(
        param.get("docid") as string,
        getUserAccount() as string,
        seq,
        param.get("type") as string //是否是查詢界面進入
      );
      //初始狀態設置
      const manager_save_flag = res[0][0].manager_save_flag;//保存Flag
      const improvement_result = res[0][0].improvement_result;//評核結果
      const sign_reusult_flag = res[0][0].sign_result_flag;//簽名結果
      const user_accept_flag = res[0][0].user_accept_flag;//用戶首次訪問Flag
      const flow_code = res[0][0].flow_code;//流程name
      let editable = false;
      let editable2 = false;
      let type = "record";
      let status = "";
      if (sign_reusult_flag === "Y") {
        //以結案狀態渲染
        status = "end";
        editable = true;
        editable2 = true;
        type = "check";
      } else {
        if (flow_code === "improve") {
          if (manager_save_flag === "N") {
            status = "record_no_save";//未保存--第一次進入狀態
          } else if (manager_save_flag === "Y") {
            status = "record_has_save";//已保存狀態
          }
          editable = false;
          editable2 = false;
          type = "record";
          UserModalOp.open({
            height: 320,
            conFirmText: "我已了解",
            cancelText: "關閉",
            title: "系統提示",
            content: [
              "考核主管您好，員工不勝任工作，需進行輔導改善，步驟如下，請知悉！",
              "第1步：主管與員工面談，制定改善計劃；",
              "第2步：員工於期限內完成改善；",
              "第3步：期限結束，主管檢核改善成果，判定是否合格；",
              "第4步：若改善不達標，主管可提報不勝任或給予繼續改善機會。",
              "注：改善總時長須≤3個",
            ],
            icon: MdOutlineWarningAmber,
            onConfirm: () => {
              UserModalOp.close();
            },
            onCancel: () => {
              UserModalOp.close();
            },
          });
        } else if (
          flow_code === "improve_record_sign_A" ||
          flow_code === "improve_record_sign_B" //改善計劃用戶確認簽名狀態
        ) {
          status = "record_sign";
          type = "record";
          editable2 = false;
          editable = true;
        } else if (
          flow_code === "improve_check_sign_A" ||
          flow_code === "improve_check_sign_B" //改善結果用戶確認簽名狀態
        ) {
          status = "check_sign";
          type = "check";
          editable = true;
          editable2 = true;
        } else if (flow_code === "improve_check") {
          status = "improve_check";//填寫改善計劃狀態 
          type = "check";
          editable = true;
          editable2 = false;
        } else {
          if (improvement_result === "") {
            status = "check_no_save";
          } else {
            status = "check_has_save";
          }
          type = "check";
          editable = false;
          editable2 = true;
        }
      }
      const resInfo: any = await GetImproveData(
        param.get("docid") as string,
        "header",
        type,
        seq
      );
      const resInfo2: any = await GetImproveData(
        param.get("docid") as string,
        "line",
        type,
        seq
      );

      if (flow_code === "improve_check_sign_B" && user_accept_flag === "N") {
        await UpdateAccFlag(param.get("docid") as string, seq, flow_code);//員工確認簽名界面進入通知
      }

      if (status !== "record_no_save") {
        form.setFieldValue(
          "improvement_theme",
          resInfo[0][0].improvement_theme
        );
        const temp = TableDataType(resInfo2[0]);
        setDataSource({
          ...dataSource,
          improvement_theme: resInfo[0][0].improvement_theme,
          improvement_result: resInfo[0][0].improvement_result,
          lines: temp,
        });
      }

      if (
        status === "record_no_save" ||
        status === "record_has_save" ||
        status === "record_sign"
      ) {
        setInitialRow({
          id: 1,
          project: "",
          purpose: "",
          limit_start: "",
          limit_end: "",
        });
      }

      if (status === "check_no_save") {
        setInitialRow({
          id: 1,
          project: "",
          purpose: "",
          limit_start: "",
          limit_end: "",
          result: "",
          is_adopt: "",
        });
      }

      setEditalbe(editable);
      setEditable2(editable2);
      setUInfo(res[0][0]);
      setStatus(status);
      setFlowType(type);
    } catch {
      message.error("系統異常");
      setSytanxFlag(true);
    }
  };

  //#endregion

  //#region 操作
  const OperationFunc = (param: ImproveDataLines, operation: string) => {
    setIsModalOpen(false);
    if (operation === "add") {
      setDataSource((prev) => {
        // 添加嚴格項目比對邏輯
        const exists = prev.lines.some(
          (item) =>
            item.project.trim().toLowerCase() ===
            param.project.trim().toLowerCase()
        );

        if (exists) {
          message.warning("此改善項目已存在，不可重複添加");
          return prev;
        }

        // 生成唯一鍵值
        const newItem = {
          ...param,
          id: prev.lines.length + 1,
        };

        return {
          ...prev,
          lines: [...prev.lines, newItem],
        };
      });
    } else {
      //修改
      const temp = dataSource.lines;
      for (let i = 0; i < temp.length; i++) {
        if (temp[i].id === param.id) {
          if (flowtype === "record") {
            temp[i].project = param.project;
            temp[i].purpose = param.purpose;
            temp[i].limit_start = param.limit_start;
            temp[i].limit_end = param.limit_end;
          } else {
            temp[i].is_adopt = param.is_adopt;
            temp[i].result = param.result;
          }
          break;
        }
      }
      setDataSource({ ...dataSource, lines: temp });
    }
  };

  //點擊更新一條記錄
  const linesEdit = (id: number) => {
    setModifyRow(dataSource.lines.filter((item) => item.id === id)[0]);
    setIsModalOpen(true);
    setOperation("modify");
    setChangeFlag(changeFlag + 1);
  };
  
  //點擊刪除一條記錄
  const linesDel = (id: number) => {
    setDataSource({
      ...dataSource,
      lines: dataSource.lines.filter((item) => item.id !== id),
    });
  };

  const closeForm = () => {
    setIsModalOpen(false);
  };

  //保存或送出
  const ImproveLines = async (ope: string) => {
    if (dataSource.lines.length === 0) {
      message.info("請填寫至少一條改善項目！");
      return false;
    }
    if (UInfo?.flow_code === "improve_check") {
      if (dataSource.improvement_result === "") {
        message.info("改善結論未選擇");
        return false;
      }
      let flag = false;
      dataSource.lines.forEach((element) => {
        if (element.result === "" || element.is_adopt === "") {
          flag = true;
        }
      });
      if (flag) {
        message.info("請將改善結果和是否達標填寫完整");
        return false;
      }
    }
    const param = {
      ...dataSource,
      operation: operation,
      type: flowtype,
      seq: curSelSeq,
      sendtype: ope,
      last_update_by: getUserAccount(),
      flow_code: UInfo?.flow_code,
      approve:
        dataSource.improvement_result === "持續改善" &&
        (UInfo?.flow_code === "improve_record_sign_A" ||
          UInfo?.flow_code === "improve_record_sign_B")
          ? "N"
          : "Y",
    };
    try {
      const res: any = await AddImproveLines(JSON.stringify(param));
      if (res === "success") {
        message.success(`${ope === "send" ? "送出" : "保存"}成功`);
        if (ope === "send") {
          setEditalbe(true)
          setEditable2(true)
          setStatus("end")
          router.push("/dashboard");
        }
      }
    } catch {
      message.error("系統後台異常，請稍後重試");
    }
  };

  //簽名取消按鈕
  const signCalcle = () => {
    setSignModalOpen(false);
  };
  //簽名提交按鈕子組件回調
  const signSubmit = () => {
    setStatus("end");
    setSignModalOpen(false);
    router.push("/dashboard");
  };
  //#endregion

  //#region JSX生成
  //選擇--第幾次改善計劃
  const seqSelect = () => {
    if (curSeq > 1) {
      const temp: { value: number; label: number }[] = [];
      for (let i = 1; i <= curSeq; i++) {
        temp.push({
          value: i,
          label: i,
        });
      }
      return (
        <>
          <span>第</span>
          <Select
            size="small"
            options={temp}
            defaultValue={curSeq}
            style={{ width: "50px", margin: "0 5px" }}
            onChange={(e) => {
              getInitData(e);
            }}
          ></Select>
          <span>項計劃書</span>
        </>
      );
    }
  };

  const getTable = () => {
    if (dataSource.lines.length > 0)
      return (
        <Table
          dataSource={dataSource.lines.map((item) => ({
            ...item,
            key: item.id,
          }))}
          bordered={true}
          pagination={false}
          className="datasource-table"
          columns={getColumns()}
          style={{ marginTop: "5px", width: "700px" }}
        ></Table>
      );
  };

  const getColumns = () => {
    const results: any = [
      {
        dataIndex: "project",
        key: "project",
        title: "改善項目",
      },
      {
        dataIndex: "purpose",
        key: "purpose",
        title: "期望目標",
      },
      {
        dataIndex: "limit_start",
        key: "limit_start",
        title: "改善期限起",
        width: 120,
      },
      {
        dataIndex: "limit_end",
        key: "limit_end",
        title: "改善期限止",
        width: 120,
      },
    ];
    if (flowtype === "record" && UInfo?.flow_code === "improve") {
      results.push({
        dataIndex: "id",
        key: "operation",
        title: "操作",
        width: 120,
        render: (ids: number) => {
          return (
            <>
              <Button
                type="primary"
                onClick={() => {
                  linesEdit(ids);
                }}
                icon={<MdEdit></MdEdit>}
              ></Button>
              <Button
                type="primary"
                onClick={() => {
                  linesDel(ids);
                }}
                danger
                icon={<MdDelete></MdDelete>}
                style={{ marginLeft: "10px" }}
              ></Button>
            </>
          );
        },
      });
    } else if (flowtype === "check") {
      results.push({
        dataIndex: "result",
        key: "result",
        title: "改善結果",
      });
      results.push({
        dataIndex: "is_adopt",
        key: "is_adopt",
        title: "是否達標",
      });
      if (UInfo?.flow_code === "improve_check") {
        results.push({
          dataIndex: "id",
          key: "operation",
          title: "操作",
          width: 60,
          render: (ids: number) => {
            return (
              <>
                <Button
                  type="primary"
                  onClick={() => {
                    linesEdit(ids);
                  }}
                  icon={<MdEdit></MdEdit>}
                ></Button>
              </>
            );
          },
        });
      }
    }
    return results;
  };

  //根據狀態生成操作按鈕
  const getOperationButton = () => {
    if (status === "record_sign" || status === "check_sign") {
      return (
        <>
          <Button
            type="primary"
            icon={<SignatureOutlined />}
            onClick={() => {
              setSignModalOpen(true);
            }}
            disabled={sytanxFlag}
            style={{ margin: "0 20px" }}
          >
            簽名
          </Button>
        </>
      );
    } else if (
      status === "record_has_save" ||
      status === "record_no_save" ||
      status === "check_has_save" ||
      status === "check_no_save" ||
      status === "improve_check"
    ) {
      return (
        <>
          <Button
            type="primary"
            icon={<SaveOutlined />}
            onClick={() => ImproveLines("save")}
            disabled={sytanxFlag}
            style={{ marginRight: "20px" }}
          >
            儲存
          </Button>
          <Button
            type="primary"
            icon={<SendOutlined />}
            danger
            disabled={sytanxFlag}
            onClick={() => ImproveLines("send")}
          >
            送出
          </Button>
        </>
      );
    }
  };

  //改善結論
  const getImproveResult = () => {
    if (UInfo?.flow_code === "improve_check") {
      return (
        <>
          <Divider style={{ margin: "10px 0", background: "gray" }}></Divider>
          <Row className="form-row">
            <h4>改善結論：</h4>
          </Row>
          <Row>
            <Radio.Group
              className="form-label-span"
              disabled={editable2}
              options={improveRadio}
              name="improvement_result"
              defaultValue={
                dataSource.improvement_result === ""
                  ? 0
                  : improveRadio.filter(
                      (item) => item.label === dataSource.improvement_result
                    )[0].value
              }
              onChange={(e: RadioChangeEvent) => {
                setDataSource({
                  ...dataSource,
                  improvement_result: improveRadio.filter(
                    (item) => item.value === e.target.value
                  )[0].label,
                });
                if (e.target.value === 3)
                  UserModalOp.open({
                    height: 340,
                    conFirmText: "我已了解",
                    cancelText: "返回主頁",
                    title: "系統提示",
                    content: [
                      "单位主管您好，公司针对不胜任员工，可通过“调岗”或“原岗培训”进行改善，具体步驟如下，请您阅读知晓：",
                      "第1步：請單位主管與員工面談，制定改善計劃，包括改善項目、目標及期限；",
                      "第2步：要求員工於期限內進行改善；",
                      "第3步：期限結束，請主管檢核員工改善成果，判定是否達標；",
                      "注：若改善不達標，主管可提報不勝任或給予繼續改善的機會。（改善總時長≤3個月）",
                    ],
                    icon: MdOutlineWarningAmber,
                    onConfirm: () => {
                      UserModalOp.close();
                    },
                    onCancel: () => {
                      UserModalOp.close();
                      router.push("/dashboard");
                    },
                  });
              }}
            ></Radio.Group>
          </Row>
        </>
      );
    }
  };

  //主管簽核有返回按鈕
  const returnManger = () => {
    if (
      UInfo?.flow_code === "manager_approve_1" ||
      UInfo?.flow_code === "manager_approve_2" ||
      UInfo?.flow_code === "manager_approve_3"
    ) {
      return (
        <Button
          type="primary"
          danger
          style={{ marginLeft: "100px" }}
          icon={<FaCircleArrowLeft />}
          onClick={() => {
            router.back();
          }}
        >
          返回
        </Button>
      );
    }
  };
  //#endregion

  //#region Render
  return (
    <>
      <div className="interview-operator-1">
        <h3 style={{ display: "inline-block", marginRight: "20px" }}>
          改善計劃書
        </h3>
        {seqSelect()}
        {returnManger()}
      </div>
      <Divider style={{ margin: "15px 0", background: "brown" }}></Divider>
      <div className="interview-box">
        <Form
          form={form}
          className="improveForm"
          name="improveForm"
          style={{ marginTop: "10px" }}
        >
          <Row className="form-row">
            <h4>人員基本信息：</h4>
          </Row>
          <Row align="middle" style={{ height: "35px" }} className="form-row">
            <Col span={8}>
              <Form.Item
                name="badge"
                colon={false}
                label={<label className="form-label">工號:</label>}
              >
                <span className="form-label-span">{UInfo?.badge}</span>
              </Form.Item>
            </Col>
            <Col span={8}>
              <Form.Item
                name="spend_type"
                colon={false}
                label={<label className="form-label">身份別:</label>}
              >
                <span className="form-label-span">{UInfo?.spend_type}</span>
              </Form.Item>
            </Col>
            <Col span={8}>
              <Form.Item
                name="dept_code"
                colon={false}
                label={<label className="form-label">單位:</label>}
              >
                <span className="form-label-span">{UInfo?.dept_code}</span>
              </Form.Item>
            </Col>
          </Row>
          <Row align="middle" style={{ height: "35px" }} className="form-row">
            <Col span={8}>
              <Form.Item
                name="chinese_name"
                colon={false}
                label={<label className="form-label">姓名:</label>}
              >
                <span className="form-label-span">{UInfo?.chinese_name}</span>
              </Form.Item>
            </Col>
            <Col span={8}>
              <Form.Item
                name="hire_date"
                colon={false}
                label={<label className="form-label">到職日:</label>}
              >
                <span className="form-label-span">{UInfo?.hire_date}</span>
              </Form.Item>
            </Col>
            <Col span={8}>
              <Form.Item
                name="position"
                colon={false}
                label={<label className="form-label">職位:</label>}
              >
                <span className="form-label-span">{UInfo?.position}</span>
              </Form.Item>
            </Col>
          </Row>
          <Divider style={{ margin: "5px 0", background: "gray" }}></Divider>
          <Row className="form-row">
            <h4>改善計劃：</h4>
          </Row>
          <Row>
            <Button
              style={{ marginRight: "30px" }}
              icon={<IoAddCircle style={{ fontSize: "16px" }}></IoAddCircle>}
              onClick={() => {
                setOperation("add");
                setIsModalOpen(true);
              }}
              disabled={sytanxFlag || editable || editable2}
              type="primary"
            >
              添加
            </Button>
            <Form.Item
              name="improvement_theme"
              colon={false}
              label={<label className="form-label">改善主題（選填）:</label>}
            >
              <Select
                className="form-change-width"
                optionFilterProp="label"
                options={improveTheme}
                disabled={editable || editable2}
                style={{ color: editable || editable2 ? "white" : "black" }}
                onChange={(e) =>
                  setDataSource({
                    ...dataSource,
                    improvement_theme: improveTheme.filter(
                      (item) => item.value === e
                    )[0].label,
                  })
                }
              ></Select>
            </Form.Item>
          </Row>
          {getTable()}
          {getImproveResult()}
          <Modal
            closable={false}
            open={isModalOpen}
            className="interview-modal"
            height={600}
            wrapClassName="single-form"
            footer={[]}
          >
            <DetailForm
              singleRow={operation === "add" ? initialRow : modifyRow}
              formsettiing={tablesettingArrImprove}
              operation={operation}
              Submit={OperationFunc}
              Cancle={closeForm}
              selectOptions={selectOptions}
              updateFlag={changeFlag}
              check_flag={UInfo?.flow_code === "improve_check" ? true : false}
            ></DetailForm>
          </Modal>
        </Form>
      </div>
      <Divider style={{ margin: "10px 0", background: "brown" }}></Divider>
      <div className="interview-operator">{getOperationButton()}</div>
      <Modal
        closable={false}
        open={signModalOpen}
        height={500}
        width={600}
        wrapClassName="single-form"
        footer={[]}
      >
        <SignCom
          docid={dataSource.docid}
          flow_code={UInfo?.flow_code as string}
          flow_phase={UInfo?.flow_phase as string}
          seq={curSelSeq}
          onCancel={() => signCalcle()}
          onSubmit={() => signSubmit()}
        ></SignCom>
      </Modal>
    </>
  );
  //#endregion
}
